package br.com.educa.modelo.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.json.RooJson;
import org.springframework.roo.addon.serializable.RooSerializable;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional;

import br.com.educa.modelo.financeiro.MovimentacoesCaixas;
import br.com.educa.modelo.financeiro.PlanoContas;
import br.com.educa.modelo.pessoa.Pessoas;
import br.com.educa.modelo.publico.Controle;
import br.com.educa.modelo.publico.ControleFuncoes;
import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;

@Entity
@Configurable
@RooJavaBean
@RooSerializable
@RooToString
@RooJson
@RooJpaActiveRecord(finders = { "findUsuariosByUsernameEquals", "findUsuariosByUsername", "findUsuariosByPessoa" })
public class Usuario implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Version
    @Column(name = "version")
    private Integer version;
	
    @PersistenceContext(unitName = "persistenceUnit")
    transient EntityManager entityManager;

    private static final long serialVersionUID = 1L;

    private String password;

    private String username;

    private boolean accountNonExpired;

    private boolean accountNonLocked;

    private boolean credentialsNonExpired;

    private boolean enabled;
    
    @ManyToOne
    @JoinColumn(name = "controle", referencedColumnName = "id")
    private Controle controle;

    @ManyToOne
    @JoinColumn(name = "pessoa", referencedColumnName = "id", nullable = false)
    private Pessoas pessoa;
    
    @OneToMany(mappedBy = "usuario")
    private List<ControleFuncoes> controleFuncoes;

    @NotNull
    @Pattern(regexp = "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$")
    private String email;

    @ManyToMany(cascade = CascadeType.DETACH, fetch = FetchType.EAGER)
    private Set<Perfil> perfis;
    
    @ManyToOne
    @JoinColumn(name = "contaPadrao", referencedColumnName = "id")
    private PlanoContas contaPadrao;

    @Override
    public Collection<org.springframework.security.core.GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> retorno = new ArrayList<GrantedAuthority>();
        for (Perfil perfil : perfis) {
            retorno.add(perfil);
        }
        if (retorno.isEmpty()) {
            retorno.add(new GrantedAuthorityImpl("ROLE_NO_ROLES"));
        }
        return retorno;
    }

    public void setPassword(String password) {
        MessageDigestPasswordEncoder passwordEncoder = new MessageDigestPasswordEncoder("MD5");
        if (password == null || password.equals("")) return;
        String encodedPassword = passwordEncoder.encodePassword(password, null);
        this.password = encodedPassword;
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Integer getVersion() {
        return this.version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }

    public static final EntityManager entityManager() {
        EntityManager em = new Usuario().entityManager;
        if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
        return em;
    }

    public static long countUsuarios() {
        return entityManager().createQuery("SELECT COUNT(o) FROM Usuario o", Long.class).getSingleResult();
    }

    public static List<br.com.educa.modelo.security.Usuario> findAllUsuarios() {
        return entityManager().createQuery("SELECT o FROM Usuario o", Usuario.class).getResultList();
    }

    public static br.com.educa.modelo.security.Usuario findUsuario(Long id) {
        if (id == null) return null;
        return entityManager().find(Usuario.class, id);
    }

    public static List<br.com.educa.modelo.security.Usuario> findUsuarioEntries(int firstResult, int maxResults) {
        return entityManager().createQuery("SELECT o FROM Usuario o", Usuario.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
    }

    @Transactional
    public void persist() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.persist(this);
    }

    @Transactional
    public void remove() {
        if (this.entityManager == null) this.entityManager = entityManager();
        if (this.entityManager.contains(this)) {
            this.entityManager.remove(this);
        } else {
            Usuario attached = Usuario.findUsuario(this.id);
            this.entityManager.remove(attached);
        }
    }

    @Transactional
    public void flush() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.flush();
    }

    @Transactional
    public void clear() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.clear();
    }

    @Transactional
    public br.com.educa.modelo.security.Usuario merge() {
        if (this.entityManager == null) this.entityManager = entityManager();
        Usuario merged = this.entityManager.merge(this);
        this.entityManager.flush();
        return merged;
    }

    public String toJson() {
        return new JSONSerializer().exclude("*.class").serialize(this);
    }

    public static br.com.educa.modelo.security.Usuario fromJsonToUsuario(String json) {
        return new JSONDeserializer<Usuario>().use(null, Usuario.class).deserialize(json);
    }

    public static String toJsonArray(Collection<br.com.educa.modelo.security.Usuario> collection) {
        return new JSONSerializer().exclude("*.class").serialize(collection);
    }

    public static Collection<br.com.educa.modelo.security.Usuario> fromJsonArrayToUsuarios(String json) {
        return new JSONDeserializer<List<Usuario>>().use(null, ArrayList.class).use("values", Usuario.class).deserialize(json);
    }

    public static TypedQuery<br.com.educa.modelo.security.Usuario> findUsuariosByUsername(String username) {
        if (username == null || username.length() == 0) throw new IllegalArgumentException("The username argument is required");
        EntityManager em = Usuario.entityManager();
        TypedQuery<Usuario> q = em.createQuery("SELECT o FROM Usuario AS o WHERE o.username = :username", Usuario.class);
        q.setParameter("username", username);
        return q;
    }

    public static TypedQuery<br.com.educa.modelo.security.Usuario> findUsuariosByUsernameEquals(String username) {
        if (username == null || username.length() == 0) throw new IllegalArgumentException("The username argument is required");
        EntityManager em = Usuario.entityManager();
        TypedQuery<Usuario> q = em.createQuery("SELECT o FROM Usuario AS o WHERE o.username = :username", Usuario.class);
        q.setParameter("username", username);
        return q;
    }

    public String toString() {
        ArrayList<String> excluidos = new ArrayList<String>();
        excluidos.add("pessoa");
        ReflectionToStringBuilder.setDefaultStyle(ToStringStyle.SHORT_PREFIX_STYLE);
        return ReflectionToStringBuilder.toStringExclude(this, excluidos);
    }

    public String getPassword() {
        return this.password;
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public boolean isAccountNonExpired() {
        return this.accountNonExpired;
    }

    public void setAccountNonExpired(boolean accountNonExpired) {
        this.accountNonExpired = accountNonExpired;
    }

    public boolean isAccountNonLocked() {
        return this.accountNonLocked;
    }

    public void setAccountNonLocked(boolean accountNonLocked) {
        this.accountNonLocked = accountNonLocked;
    }

    public boolean isCredentialsNonExpired() {
        return this.credentialsNonExpired;
    }

    public void setCredentialsNonExpired(boolean credentialsNonExpired) {
        this.credentialsNonExpired = credentialsNonExpired;
    }

    public boolean isEnabled() {
        return this.enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public String getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Set<Perfil> getPerfis() {
		return perfis;
	}

	public void setPerfis(Set<Perfil> perfis) {
		this.perfis = perfis;
	}

	public Pessoas getPessoa() {
        return this.pessoa;
    }

    public void setPessoa(Pessoas pessoa) {
        this.pessoa = pessoa;
    }

	public static TypedQuery<Usuario> findUsuariosByPessoa(Pessoas pessoa) {
        if (pessoa == null) throw new IllegalArgumentException("The pessoa argument is required");
        EntityManager em = Usuario.entityManager();
        TypedQuery<Usuario> q = em.createQuery("SELECT o FROM Usuario AS o WHERE o.pessoa = :pessoa", Usuario.class);
        q.setParameter("pessoa", pessoa);
        return q;
    }
	
	public static TypedQuery<Usuario> findUsuariosByPessoaAutoComplete(String pessoa) {
        if (pessoa == null) throw new IllegalArgumentException("The pessoa argument is required");
        EntityManager em = Usuario.entityManager();
        TypedQuery<Usuario> q = em.createQuery("SELECT o FROM Usuario AS o, Pessoa as p WHERE o.pessoa = p.id AND LOWER(p.nome) LIKE LOWER(:pessoa)", Usuario.class);
        q.setParameter("pessoa", "%"+pessoa+"%");
        return q;
    }

	public PlanoContas getContaPadrao() {
        return this.contaPadrao;
    }

	public void setContaPadrao(PlanoContas contaPadrao) {
        this.contaPadrao = contaPadrao;
    }
}
